package org.dromara.system.controller.system;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.service.MinioService;
import org.dromara.common.core.validate.QueryGroup;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.minio.config.PathConfig;
import org.dromara.common.minio.config.ServerConfig;
import org.dromara.common.minio.constant.Constants;
import org.dromara.common.minio.utils.StringUtils;
import org.dromara.common.minio.utils.file.FileUploadUtils;
import org.dromara.common.minio.utils.file.FileUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseService;
import org.dromara.system.domain.bo.SysMinioBo;
import org.dromara.system.domain.bo.SysOssBo;
import org.dromara.system.domain.vo.SysMinioUploadVo;
import org.dromara.system.domain.vo.SysMinioVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysMinioService;
import org.dromara.system.service.ISysOssService;
import org.dromara.wms.domain.WmsProductMinio;
import org.dromara.wms.service.WmsProductMinioServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传 控制层
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/resource/minio")
public class SysMinioController extends BaseService
{
  private static final Logger log = LoggerFactory.getLogger(SysMinioController.class);

  @Autowired
  private ServerConfig serverConfig;
  private WmsProductMinioServiceImpl wmsProductMinioService;
  private final ISysMinioService minioService;

  private static final String FILE_DELIMETER = ",";

  /**
   * 通用下载请求
   *
   * @param fileName 文件名称
   * @param delete 是否删除
   */
  @GetMapping("/download")
  public void fileDownload(String fileName, Boolean delete, javax.servlet.http.HttpServletResponse response, HttpServletRequest request)
  {
    try
    {
      if (!FileUtils.checkAllowDownload(fileName))
      {
        throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
      }
      String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
      String filePath = PathConfig.getDownloadPath() + fileName;

      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      FileUtils.setAttachmentResponseHeader(response, realFileName);
      FileUtils.writeBytes(filePath, response.getOutputStream());
      if (delete)
      {
        FileUtils.deleteFile(filePath);
      }
    }
    catch (Exception e)
    {
      log.error("下载文件失败", e);
    }
  }

  /**
   * 通用上传请求（单个）
   */
  @PostMapping("/upload")
  public void uploadFile(MultipartFile file) throws Exception
  {

    // 上传文件路径
    String filePath = PathConfig.getUploadPath();
    // 上传并返回新文件名称
    String fileName = FileUploadUtils.upload(filePath, file);
  }

  /**
   * 通用上传请求（多个）
   */
  @PostMapping("/uploads")
  public void uploadFiles(List<MultipartFile> files) throws Exception
  {
    // 上传文件路径
    String filePath = PathConfig.getUploadPath();
    List<String> urls = new ArrayList<String>();
    List<String> fileNames = new ArrayList<String>();
    List<String> newFileNames = new ArrayList<String>();
    List<String> originalFilenames = new ArrayList<String>();
    for (MultipartFile file : files)
    {
      // 上传并返回新文件名称
      String fileName = FileUploadUtils.upload(filePath, file);
      String url = serverConfig.getUrl() + fileName;
      urls.add(url);
      fileNames.add(fileName);
      newFileNames.add(FileUtils.getName(fileName));
      originalFilenames.add(file.getOriginalFilename());
    }

  }

  /**
   * 本地资源通用下载
   */
  @GetMapping("/download/resource")
  public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    try
    {
      if (!FileUtils.checkAllowDownload(resource))
      {
        throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
      }
      // 本地资源路径
      String localPath = PathConfig.getProfile();
      // 数据库资源地址
      String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
      // 下载名称
      String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      FileUtils.setAttachmentResponseHeader(response, downloadName);
      FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
    catch (Exception e)
    {
      log.error("下载文件失败", e);
    }
  }




//  @PostMapping("/uploadFileMinio")
//  public void  uploadFileMinio(MultipartFile file) throws Exception{
//    String s = FileUploadUtils.uploadMinio(file);
//
//    System.out.println("url:"+s);
//    System.out.println("fileName:"+s);
//    System.out.println("newFileName:"+FileUtils.getName(s));
//    System.out.println("originalFileName"+file.getOriginalFilename());
//
//  }



  @SaCheckPermission("system:minio:uploadFileMinio")
  @Log(title = "Minio对象存储", businessType = BusinessType.INSERT)
  @PostMapping(value = "/uploadFileMinio", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public R<SysMinioUploadVo> uploadFileMinio(@RequestPart("file") MultipartFile file,
                                  @RequestParam(value = "treeValue", required = false) String treeValue,
                                  @RequestParam(value = "name", required = false) String name,
                                  @RequestParam(value = "fileName", required = false) String fileName,
                                  @RequestParam(value = "productId", required = false) Long productId
  ) {
    if (ObjectUtil.isNull(file)) return R.fail("上传文件不能为空");

    SysMinioVo minioVo = new SysMinioVo();




    try {
      SysMinioVo minio = minioService.upload(file, treeValue, name, fileName);
//      String s = FileUploadUtils.uploadMinio(file);
      minioVo.setUrl(minio.getUrl());
      System.out.println("url:"+minio.getUrl());
      System.out.println("fileName:"+fileName);
      System.out.println("newFileName:"+FileUtils.getName(minio.getFileName()));
      System.out.println("originalFileName"+file.getOriginalFilename());
      //中间表
      if (productId != null){
        WmsProductMinio wmsProductMinioBo = new WmsProductMinio();
        wmsProductMinioBo.setProductId(productId);
        wmsProductMinioBo.setMinioId(minioVo.getMinioId());
        wmsProductMinioBo.setSort(wmsProductMinioService.countAll(productId));
        wmsProductMinioService.insertByBo(wmsProductMinioBo);
      }
      SysMinioUploadVo uploadVo = new SysMinioUploadVo();
      uploadVo.setUrl(minio.getUrl());
      uploadVo.setFileName(file.getOriginalFilename());
      uploadVo.setMinioUrl(minioVo.getUrl().toString());
      return R.ok(uploadVo);
    }catch (Exception e){
      throw new RuntimeException(e);
    }
  }

  @SaCheckPermission("system:minio:list")
  @GetMapping("/list")
  public TableDataInfo<SysMinioVo> list(@Validated(QueryGroup.class) SysMinioBo bo, PageQuery pageQuery) {
    return minioService.queryPageList(bo, pageQuery);
  }

}
